<template>
  <div class="user-management-container">
    <div class="user-management">
      <!-- 页面标题 -->
      <div class="page-title">
        <h2>用户管理</h2>
      </div>

      <!-- 顶部操作栏 -->
      <div class="operation-bar">
        <div class="left">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户ID/用户名"
            class="search-input"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="statusFilter" placeholder="状态" @change="handleSearch">
            <el-option label="全部" value="" />
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </div>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>
      </div>

      <!-- 用户表格 -->
      <el-card class="table-card">
        <div class="table-container">
          <el-table
            :data="filteredUsers"
            style="width: 100%"
            :stripe="true"
            v-loading="loading"
            height="calc(100vh - 340px)"
          >
            <el-table-column 
              prop="id" 
              label="用户ID" 
              width="120"
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column 
              prop="name" 
              label="用户名" 
              width="120" 
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column 
              prop="password" 
              label="密码" 
              width="120" 
              align="center"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span>{{ scope.row.password }}</span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="role" 
              label="角色" 
              width="120" 
              align="center"
              :show-overflow-tooltip="true"
            />
            <el-table-column 
              prop="status" 
              label="状态" 
              width="120" 
              align="center"
            >
              <template #default="scope">
                <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                  {{ scope.row.status === 'active' ? '正常' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column 
              label="操作" 
              min-width="120"
              align="center"
            >
              <template #default="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    link
                    @click="handleEdit(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    :type="scope.row.status === 'active' ? 'danger' : 'success'"
                    link
                    @click="handleStatusChange(scope.row)"
                  >
                    {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页器 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
        v-model="dialogVisible"
        width="460px"
        destroy-on-close
      >
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="rules"
          label-width="80px"
          status-icon
        >
          <el-form-item label="用户名" prop="name">
            <el-input v-model="userForm.name" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
            <el-input
              v-model="userForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-input v-model="userForm.role" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// 数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)

const userForm = reactive({
  id: '',
  name: '',
  password: '',
  role: '用户',
  status: 'active'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 本地存储的key
const STORAGE_KEY = 'user_management_data'

// 从localStorage获取数据的方法
const getStorageData = () => {
  const data = localStorage.getItem(STORAGE_KEY)
  return data ? JSON.parse(data) : [
    // 默认数据
    { id: 'EMP001', name: '张三', password: 'abc123', role: '用户', status: 'active' },
    { id: 'EMP002', name: '李四', password: 'def456', role: '用户', status: 'active' },
    { id: 'EMP003', name: '王五', password: 'ghi789', role: '用户', status: 'disabled' },
    { id: 'EMP004', name: '赵六', password: 'jkl012', role: '用户', status: 'active' },
    { id: 'EMP005', name: '陈七', password: 'mno345', role: '用户', status: 'active' },
    { id: 'EMP006', name: '周八', password: 'pqr678', role: '用户', status: 'disabled' },
    { id: 'EMP007', name: '吴九', password: 'stu901', role: '用户', status: 'active' },
    { id: 'EMP008', name: '郑十', password: 'vwx234', role: '用户', status: 'active' },
    { id: 'EMP009', name: '孙十一', password: 'yz1234', role: '用户', status: 'disabled' },
    { id: 'EMP010', name: '杨十二', password: 'abc567', role: '用户', status: 'active' }
  ]
}

// 保存数据到localStorage的方法
const saveToStorage = (data) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
}

// 修改用户数据的定义
const users = ref(getStorageData())

// 在数据变化时保存到localStorage
const updateAndSave = (newData) => {
  users.value = newData
  saveToStorage(newData)
}

// 过滤后的用户列表
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    const matchQuery = user.name.includes(searchQuery.value) || 
                      user.id.includes(searchQuery.value)
    const matchStatus = !statusFilter.value || user.status === statusFilter.value
    return matchQuery && matchStatus
  })
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleAdd = () => {
  dialogType.value = 'add'
  userForm.id = ''
  userForm.name = ''
  userForm.password = ''
  userForm.role = '用户'
  userForm.status = 'active'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const newUsers = users.value.map(user => {
      if (user.id === row.id) {
        return {
          ...user,
          status: user.status === 'active' ? 'disabled' : 'active'
        }
      }
      return user
    })
    
    updateAndSave(newUsers)
    ElMessage.success('操作成功')
  } catch (error) {
    // 用户取消操作
  }
}

const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate((valid) => {
    if (valid) {
      const newUsers = [...users.value]
      
      if (dialogType.value === 'add') {
        // 生成新的用户ID
        const newId = 'EMP' + String(users.value.length + 1).padStart(3, '0')
        newUsers.push({
          id: newId,
          name: userForm.name,
          password: userForm.password,
          role: userForm.role,
          status: userForm.status
        })
      } else {
        // 编辑现有用户
        const index = newUsers.findIndex(u => u.id === userForm.id)
        if (index !== -1) {
          newUsers[index] = { ...userForm }
        }
      }
      
      updateAndSave(newUsers)
      dialogVisible.value = false
      ElMessage.success('操作成功')
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 组件挂载时初始化数据
onMounted(() => {
  users.value = getStorageData()
})
</script>

<style scoped>
.user-management-container {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.user-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-title {
  margin: 0;
  padding: 0;
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #1f2f3d;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-bar .left {
  display: flex;
  gap: 12px;
}

.search-input {
  width: 240px;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  flex: 1;
  overflow: hidden;
}

:deep(.el-card__body) {
  height: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  flex: 1;
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #f5f7fa;
  --el-table-border-color: #ebeef5;
}

:deep(.el-table__header) {
  font-weight: 600;
}

:deep(.el-table .cell) {
  padding: 0 8px;
  white-space: nowrap;
}

.pagination {
  margin-top: 16px;
  padding: 0;
  display: flex;
  justify-content: flex-end;
  background-color: transparent;
  z-index: 1;
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style>
